package cn.exrick.xboot.common.utils.jiuqi.utils.socketXTB.monitor.server;


import cn.exrick.xboot.common.jiuqiCommon.callAPIUtil.CallSMSservice;
import cn.exrick.xboot.common.utils.SpringUtils;
import cn.exrick.xboot.modules.ReceiveSMS.entity.ReceiveSMS;
import cn.exrick.xboot.modules.ReceiveSMS.service.IReceiveSMSService;
import cn.exrick.xboot.modules.callApi.entity.SMS;
import cn.exrick.xboot.modules.system.entity.System;
import cn.exrick.xboot.modules.system.service.ISystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.*;


@Order(value = 1)
@Slf4j
public class ServerHeart extends Thread {
    Object obj = new Object();

    private static ISystemService iSystemService  = (ISystemService) SpringUtils.getBean("ISystemServiceImpl");
    private static GetConfig getConfig  = (GetConfig) SpringUtils.getBean("getConfig");
    private static IReceiveSMSService iReceiveSMSService  = (IReceiveSMSService) SpringUtils.getBean("IReceiveSMSServiceImpl");
    private  CallSMSservice callSMSservice =new CallSMSservice();
    private ServerSocket server = null;
    public static final Map<String,Date> map = new HashMap();//时间表对应集合
    public static final Map<String,Object> systemmap = new HashMap();//对象集合
    public static final Map<String,Integer> smsmap = new HashMap();//记录预警短信发送次数的集合
    @Override
    public void run() {
        try {
            //add njp begin
            Date date = new Date();
            Map param=new HashMap();
           /* param.put("warning_status","start");//查询短信预警状态开启的数据
            Collection<System> list = iSystemService.listByMap(param);*/
            List<System> list = iSystemService.list();
            //第一次执行初始化对应实体集合与对应时间表集合
            log.info("第一次查询系统个数:"+list.size());
            for (System system : list) {
                System   sys =new System();
                sys.setId(system.getId());
                systemmap.put(system.getModuleName(),sys);
                map.put(system.getModuleName(), date);
                smsmap.put(system.getModuleName(),0);
            }
            long startTime=1000*10;
            long sendTime=1000*5;//对接系统心跳间隔时间
            //开启一个定时来检测服务的链接状态
            new Timer().scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                  //  log.info("心跳时间："+getConfig.getHeartbeat());
                    Date now = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    for (Map.Entry<String,Date> m : map.entrySet()) {

                           //log.info("key:" + m.getKey() + " value:" + m.getValue());
                           if((m.getValue().getTime()+Long.decode(getConfig.getHeartbeat()))>now.getTime()){
                               //log.info(m.getKey()+"服务链接正常");
                               //连接正常将数据库表数据状态修改成 正常
                               System sys =(System) systemmap.get(m.getKey());
                               sys.setConnStatus("1");
                               boolean b = iSystemService.saveOrUpdate(sys);
                               smsmap.put(m.getKey(),0);//连接正常初始状态值
                           }else{
                               //log.info(m.getKey()+"服务链接异常");
                               //1.连接失败将数据库表数据状态修改成 异常
                               System sys =(System) systemmap.get(m.getKey());
                               sys.setConnStatus("2");
                               iSystemService.saveOrUpdate(sys);
                               //2.发送短信预警（只发送短信预警开启的应用人员"warning_status"="start"）
                               Integer sum = smsmap.get(m.getKey());
                               //预警短信只在一定时间
                               if(sum==0){
                                   //发送短信前先判断该服务是否开启预警
                                   System sysbyId = iSystemService.getById(sys.getId());
                                   if("start".equals(sysbyId.getWarningStatus())){
                                        Map<String,Object>  sendsms=new HashMap();
                                       sendsms.put("sys_id",sys.getId());
                                       Collection<ReceiveSMS> receiveSMS = iReceiveSMSService.listByMap(sendsms);

                                       for (ReceiveSMS receiveSM : receiveSMS) {
                                           //发送短信
                                           log.info("发送"+m.getKey()+"的短信预警");
                                           SMS sms=new SMS();
                                           sms.setDESTADDR(receiveSM.getTelephone());
                                           sms.setMESSAGECONTENT(m.getKey()+"连接异常");
                                           boolean b = callSMSservice.sendSMS(sms);
                                           java.lang.System.out.println("调用短信接口："+b);
                                       }
                                       smsmap.put(m.getKey(),1);
                                   }
                               }else{
                                   //短信已发送
                                   continue;
                               }
                           }
                    }
                }
            },0,startTime);
            //add njp end
            server = new ServerSocket(30000);
            while (true) {
                Socket client = server.accept();
                synchronized (obj) {
                    new Thread(new Client(client)).start();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 客户端线程
     *
     * @author USER
     */
    class Client implements Runnable {
        Socket client;

        public Client(Socket client) {
            this.client = client;
        }

        @Override
        public void run() {
            try {

                while (true) {
                    try{
                        ObjectInput in = new ObjectInputStream(client.getInputStream());
                        //log.info("ip:" + client.getInetAddress());
                        //add njp 向下转型 begin
                       /* Entity entity = (Entity) in.readObject();
                        map.put(entity.getName(), new Date());*/
                        String entity = (String) in.readObject();
                        log.info("entity"+entity);
                        if(map.containsKey(entity)){
                            //key 存在
                            map.put(entity, new Date());
                        }
                    }catch (Exception e){
                        continue;
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //删除集合元素
    public void delSys(System sys){
        log.info("id:"+sys.getId());
        log.info("moduleName:"+sys.getModuleName());
         map.remove(sys.getModuleName());
        systemmap.remove(sys.getModuleName());
        smsmap.remove(sys.getModuleName());
        log.info(map.size()+","+systemmap.size()+","+smsmap.size());
    }
    //添加集合元素
    public void addSys(System sys){
        if(sys.getModuleName()==null){
        map.put(sys.getModuleName(),new Date());
        systemmap.put(sys.getModuleName(),sys);
        smsmap.put(sys.getModuleName(),0);
        log.info(map.size()+","+systemmap.size()+","+smsmap.size());
        }
    }
    /**
     * 程序的入口main方法
     *
     * @param args
     */
    public static void main(String[] args) {
        log.info("开始检测客户端是否在线...");
        new ServerHeart().start();
        //new ServerHeart().delSys();
    }


}
